package com.wx.mp.controller;

import com.alibaba.fastjson.JSONObject;
import com.wx.mp.config.WxMpConfiguration;
import com.wx.mp.utils.BizResult;
import com.wx.mp.utils.BizResultVO;
import com.wx.mp.utils.ErrorType;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.result.WxMpOAuth2AccessToken;
import me.chanjar.weixin.mp.bean.result.WxMpUser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

/**
 * @author Edward
 */
@Controller
@RequestMapping("/wx/redirect/{appid}")
public class WxRedirectController {

    private static final Logger logger = LoggerFactory.getLogger(WxRedirectController.class);

    @RequestMapping("/greet")
    public String greetUser(@PathVariable String appid, @RequestParam String code, ModelMap map) {

        WxMpService mpService = WxMpConfiguration.getMpServices().get(appid);

        try {
            WxMpOAuth2AccessToken accessToken = mpService.oauth2getAccessToken(code);
            WxMpUser user = mpService.oauth2getUserInfo(accessToken, null);
            map.put("user", user);
        } catch (WxErrorException e) {
            e.printStackTrace();
        }

        return "greet_user";
    }

    @RequestMapping("/getUserOpenId")
    @ResponseBody
    public BizResultVO<String> greetUserOpenId(@RequestParam String appid, @RequestParam String code) {
        logger.info("begin获取用户openId,appid={},code={}",appid,code);
        BizResult<String> result = new BizResult<String>();
        String openId="";
        WxMpService mpService = WxMpConfiguration.getMpServices().get(appid);

        try {
            WxMpOAuth2AccessToken accessToken = mpService.oauth2getAccessToken(code);
            WxMpUser user = mpService.oauth2getUserInfo(accessToken, null);
            logger.info("通过code获取到的用户信息={}", JSONObject.toJSON(user));
            openId = user.getOpenId();
        } catch (WxErrorException e) {
            e.printStackTrace();
        }
        if(!StringUtils.isEmpty(openId)){
            result.setData(openId);
            result.setErrCode(ErrorType.BIZ_SUCCESS);
            result.setErrMsg("获取openId成功");

        }else{
            result.setData(openId);
            result.setErrCode(ErrorType.BIZ_ERROR);
            result.setErrMsg("获取openId失败");
        }
        logger.info("end获取用户openId=【{}】",openId);
        return new BizResultVO<String>(result) ;
    }
}
